package com.example.mynewsapp.fragment.video

import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewsapp.R
import com.example.mynewsapp.activity.DetailNews
import com.example.mynewsapp.activity.DetailVideo
import com.example.mynewsapp.activity.DetailVideo.Companion.DETAIL_VIDEO
import com.example.mynewsapp.adapter.VideoAdapter
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.Fragment.mActivity
import com.example.mynewsapp.fragment.Fragment.video_adapter
import com.example.mynewsapp.model.VideoItem
import kotlinx.android.synthetic.main.delete_dialog.view.*
import kotlinx.android.synthetic.main.news_view.down_pull_update
import kotlinx.android.synthetic.main.video_view.newsList
import kotlinx.android.synthetic.main.video_view.recycler_view

abstract class FragmentVideoHisandFavor : Fragment(){

    abstract fun getTableName() :String

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.video_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view.setLayoutManager(LinearLayoutManager(context))
        recycler_view.setHasFixedSize(true)
        recycler_view.hideShimmerAdapter()
        newsList.setVisibility(View.GONE)

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        generateDummyList()

        down_pull_update.setColorSchemeResources(R.color.colorPrimaryDark)
        down_pull_update.setOnRefreshListener {
            var handler = Handler()
            handler.postDelayed({
                generateDummyList()
                down_pull_update.isRefreshing = false
                refreshSuccess()
            }, 1000)
        }
    }

    private fun generateDummyList() {

        val list = ArrayList<VideoItem>()
        val cursor = db!!.query(getTableName(), null, null, null, null, null, null)

        while (cursor.moveToNext()) {

            val image = cursor.getString(cursor.getColumnIndex("videoImage"))
            val title = cursor.getString(cursor.getColumnIndex("videoTitle"))
            val desc = cursor.getString(cursor.getColumnIndex("videoDesc"))
            val provider = cursor.getString(cursor.getColumnIndex("videoProvider"))
            val date = cursor.getString(cursor.getColumnIndex("videoDate"))
            val url = cursor.getString(cursor.getColumnIndex("videoUrl"))

            var like  = ""
            if (getTableName()=="videoHistory") {
                like = "no"
                val cursor1 = db!!.query("videoFavorite", null, null, null, null, null, null)
                while (cursor1.moveToNext()) {
                    val url_db = cursor1.getString(cursor1.getColumnIndex("videoUrl"))
                    if (url_db == url) {
                        like = "yes"
                        break
                    }
                }
            } else {
                like = cursor.getString(cursor.getColumnIndex("videoLike"))
            }

            val item = VideoItem(image, title, desc, provider, date, url, like)
            list += item
        }
        cursor.close() // 关闭游标，释放资源
        if (list.isEmpty()) {
            onSetList(list)
            tips()
        } else {
            onSetList(sortList(list))
        }
    }

    private fun sortList(list: ArrayList<VideoItem>): ArrayList<VideoItem> {
        val arr = ArrayList<VideoItem>()
        var length = list.size - 1
        while (length >= 0) {
            arr += list[length]
            length--
        }
        return arr
    }

    // 设置列表
    private fun onSetList(list: ArrayList<VideoItem>) {

        if (recycler_view == null) return

        recycler_view.layoutManager = LinearLayoutManager(context)
        video_adapter = VideoAdapter(list, context!!)
        recycler_view.adapter = video_adapter
        video_adapter!!.notifyDataSetChanged()
        recycler_view.hideShimmerAdapter()
        newsList.visibility = View.VISIBLE

        video_adapter?.mOnRecyclerViewItemClick = object :
                VideoAdapter.OnRecyclerViewItemClick {
            override fun OnItemClick(view: View?, content: VideoItem, position: Int) {
                val intent = Intent(context, DetailVideo::class.java)

                ifNewsExist(content)
                addData(content)

                intent.putExtra(DETAIL_VIDEO, content)
                startActivity(intent)
            }

            override fun OnLongClick(view: View?, content: VideoItem, position: Int) {
                val dialogView = LayoutInflater.from(mActivity).inflate(R.layout.delete_dialog, null)
                val builder = AlertDialog.Builder(mActivity)
                        .setView(dialogView)
                        .setTitle(R.string.deleteFavorTitle)
                val alertDialog = builder.show()

                dialogView.delete_dialog.setText(R.string.deleteFavorite)
                dialogView.delete_cancel.setText(R.string.cancelBtn)
                dialogView.delete_confirm.setText(R.string.confirmBtn)

                dialogView.delete_confirm.setOnClickListener {
                    alertDialog.dismiss()
                    db!!.delete(getTableName(), "videoUrl=?", arrayOf(content.url))
                    generateDummyList()
                }
                dialogView.delete_cancel.setOnClickListener {
                    alertDialog.dismiss()
                }
            }
        }
    }

    private fun addData (content: VideoItem) {
        // videoImage  videoTitle  videoDesc  videoIcon  videoProvider videoDate  videoUrl  videoLike
        if (content.url == "") return
        //创建存放数据的ContentValues对象
        val values = ContentValues()
        values.put("videoImage", content.image)
        values.put("videoTitle", content.title)
        values.put("videoDesc", content.desc)
        values.put("videoProvider", content.provider)
        values.put("videoDate", content.date)
        values.put("videoUrl", content.url)
        values.put("videoLike", content.like)
        //数据库执行插入命令
        db!!.insert("videoHistory", null, values)

    }

    private fun ifNewsExist (content: VideoItem){
        if (content.url == "") return
        val cursor = db!!.query("videoHistory", null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("videoUrl"))
            if (url == content.url) {
                db!!.delete("videoHistory","videoUrl=?", arrayOf(url))
                break
            }
        }
        cursor.close() // 关闭游标，释放资源
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    private fun tips() {
        if (this.isAdded) {
            Toast.makeText(mActivity, getString(R.string.noFavorite), Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshSuccess() {
        if (this.isAdded) {
            Toast.makeText(mActivity, getString(R.string.refreshSuccess), Toast.LENGTH_SHORT).show()
        }
    }

}